<?php
namespace app\api\controller;

use app\common\controller\BaseController;
use app\common\repositories\merchant\MerchantRepository;
use support\Request;

/**
 * 商户管理控制器
 * 处理商户注册、登录、API密钥管理、统计数据等
 */
class MerchantController extends BaseController
{
    protected $repository;

    public function __construct()
    {
        $this->repository = new MerchantRepository();
    }

    /**
     * 商户注册
     * @api {post} /merchant/register 商户注册
     * @apiParam {String} company_name 公司名称
     * @apiParam {String} contact_name 联系人姓名
     * @apiParam {String} email 邮箱地址
     * @apiParam {String} phone 手机号码
     * @apiParam {String} password 密码
     * @apiParam {String} password_confirm 确认密码
     */
    public function register()
    {
        $data = request()->post();
        
        // 参数验证
        $rules = [
            'company_name' => 'required|min:2|max:100',
            'contact_name' => 'required|min:2|max:50',
            'email' => 'required|email',
            'phone' => 'required|regex:/^1[3-9]\d{9}$/',
            'password' => 'required|min:8|confirmed',
            'password_confirm' => 'required'
        ];

        $errors = $this->validate($data, $rules);
        if ($errors) {
            return json(['code' => 400, 'msg' => 'Validation failed', 'errors' => $errors]);
        }

        $result = $this->repository->registerMerchant($data);
        return json($result);
    }

    /**
     * 商户登录
     * @api {post} /merchant/login 商户登录
     * @apiParam {String} email 邮箱地址
     * @apiParam {String} password 密码
     */
    public function login()
    {
        $email = request()->post('email');
        $password = request()->post('password');

        if (empty($email) || empty($password)) {
            return json(['code' => 400, 'msg' => 'Email and password are required']);
        }

        $result = $this->repository->loginMerchant($email, $password);
        return json($result);
    }

    /**
     * 邮箱验证
     * @api {get} /merchant/verify-email 邮箱验证
     * @apiParam {String} token 验证令牌
     */
    public function verifyEmail()
    {
        $token = request()->get('token');
        
        if (empty($token)) {
            return json(['code' => 400, 'msg' => 'Verification token is required']);
        }

        $result = $this->repository->verifyEmail($token);
        return json($result);
    }

    /**
     * 获取商户详情
     * @api {get} /merchant/profile 获取商户详情
     * @apiHeader {String} Authorization Bearer token
     */
    public function profile()
    {
        $merchantId = $this->getMerchantIdFromToken();
        
        if (!$merchantId) {
            return json(['code' => 401, 'msg' => 'Invalid or expired token']);
        }

        $result = $this->repository->getMerchantDetail($merchantId);
        return json($result);
    }

    /**
     * 更新商户信息
     * @api {put} /merchant/profile 更新商户信息
     * @apiHeader {String} Authorization Bearer token
     * @apiParam {String} [company_name] 公司名称
     * @apiParam {String} [contact_name] 联系人姓名
     * @apiParam {String} [phone] 手机号码
     */
    public function updateProfile()
    {
        $merchantId = $this->getMerchantIdFromToken();
        
        if (!$merchantId) {
            return json(['code' => 401, 'msg' => 'Invalid or expired token']);
        }

        $data = request()->post();
        
        // 只允许更新特定字段
        $allowedFields = ['company_name', 'contact_name', 'phone'];
        $updateData = [];
        
        foreach ($allowedFields as $field) {
            if (isset($data[$field])) {
                $updateData[$field] = $data[$field];
            }
        }

        if (empty($updateData)) {
            return json(['code' => 400, 'msg' => 'No valid fields to update']);
        }

        // 这里应该调用repository的更新方法
        // 暂时返回成功响应
        return json(['code' => 200, 'msg' => 'Profile updated successfully']);
    }

    /**
     * 创建API密钥
     * @api {post} /merchant/api-keys 创建API密钥
     * @apiHeader {String} Authorization Bearer token
     * @apiParam {String} name 密钥名称
     * @apiParam {Array} [permissions] 权限数组 ['read', 'write']
     */
    public function createApiKey()
    {
        $merchantId = $this->getMerchantIdFromToken();
        
        if (!$merchantId) {
            return json(['code' => 401, 'msg' => 'Invalid or expired token']);
        }

        $name = request()->post('name');
        $permissions = request()->post('permissions', ['read', 'write']);

        if (empty($name)) {
            return json(['code' => 400, 'msg' => 'API key name is required']);
        }

        $result = $this->repository->createApiKey($merchantId, $name, $permissions);
        
        return json([
            'code' => 200,
            'msg' => 'API key created successfully',
            'data' => $result
        ]);
    }

    /**
     * 获取API密钥列表
     * @api {get} /merchant/api-keys 获取API密钥列表
     * @apiHeader {String} Authorization Bearer token
     */
    public function getApiKeys()
    {
        $merchantId = $this->getMerchantIdFromToken();
        
        if (!$merchantId) {
            return json(['code' => 401, 'msg' => 'Invalid or expired token']);
        }

        try {
            $apiKeys = $this->repository->getApiKeys($merchantId);
            
            return json([
                'code' => 200,
                'data' => [
                    'api_keys' => $apiKeys,
                    'total' => count($apiKeys)
                ]
            ]);
        } catch (\Exception $e) {
            return json([
                'code' => 500,
                'msg' => 'Failed to retrieve API keys: ' . $e->getMessage()
            ]);
        }
    }

    /**
     * 删除API密钥
     * @api {delete} /merchant/api-keys/:id 删除API密钥
     * @apiHeader {String} Authorization Bearer token
     * @apiParam {Integer} id API密钥ID
     */
    public function deleteApiKey($id)
    {
        $merchantId = $this->getMerchantIdFromToken();
        
        if (!$merchantId) {
            return json(['code' => 401, 'msg' => 'Invalid or expired token']);
        }

        if (empty($id)) {
            return json(['code' => 400, 'msg' => 'API key ID is required']);
        }

        try {
            $result = $this->repository->deleteApiKey($merchantId, $id);
            return json($result);
        } catch (\Exception $e) {
            return json([
                'code' => 500,
                'msg' => 'Failed to delete API key: ' . $e->getMessage()
            ]);
        }
    }

    /**
     * 获取商户统计数据
     * @api {get} /merchant/stats 获取商户统计数据
     * @apiHeader {String} Authorization Bearer token
     * @apiParam {String} [start_date] 开始日期 (Y-m-d)
     * @apiParam {String} [end_date] 结束日期 (Y-m-d)
     */
    public function getStats()
    {
        $merchantId = $this->getMerchantIdFromToken();
        
        if (!$merchantId) {
            return json(['code' => 401, 'msg' => 'Invalid or expired token']);
        }

        $startDate = request()->get('start_date', date('Y-m-d', strtotime('-30 days')));
        $endDate = request()->get('end_date', date('Y-m-d'));

        $result = $this->repository->getMerchantStats($merchantId, $startDate, $endDate);
        return json($result);
    }

    /**
     * 获取实时统计数据
     * @api {get} /merchant/realtime-stats 获取实时统计数据
     * @apiHeader {String} Authorization Bearer token
     */
    public function getRealtimeStats()
    {
        $merchantId = $this->getMerchantIdFromToken();
        
        if (!$merchantId) {
            return json(['code' => 401, 'msg' => 'Invalid or expired token']);
        }

        // 这里应该调用repository的获取实时统计数据方法
        // 暂时返回模拟数据
        return json([
            'code' => 200,
            'data' => [
                'today_clicks' => 1250,
                'today_installs' => 89,
                'today_registers' => 45,
                'conversion_rate' => 7.12,
                'active_apps' => 3,
                'api_usage' => [
                    'today' => 2847,
                    'limit' => 10000,
                    'percentage' => 28.47
                ]
            ]
        ]);
    }

    /**
     * 修改密码
     * @api {post} /merchant/change-password 修改密码
     * @apiHeader {String} Authorization Bearer token
     * @apiParam {String} current_password 当前密码
     * @apiParam {String} new_password 新密码
     * @apiParam {String} new_password_confirm 确认新密码
     */
    public function changePassword()
    {
        $merchantId = $this->getMerchantIdFromToken();
        
        if (!$merchantId) {
            return json(['code' => 401, 'msg' => 'Invalid or expired token']);
        }

        $currentPassword = request()->post('current_password');
        $newPassword = request()->post('new_password');
        $newPasswordConfirm = request()->post('new_password_confirm');

        if (empty($currentPassword) || empty($newPassword) || empty($newPasswordConfirm)) {
            return json(['code' => 400, 'msg' => 'All password fields are required']);
        }

        if ($newPassword !== $newPasswordConfirm) {
            return json(['code' => 400, 'msg' => 'New passwords do not match']);
        }

        if (strlen($newPassword) < 8) {
            return json(['code' => 400, 'msg' => 'New password must be at least 8 characters'];
        }

        // 这里应该调用repository的修改密码方法
        // 暂时返回成功响应
        return json(['code' => 200, 'msg' => 'Password changed successfully']);
    }

    /**
     * 重置API密钥
     * @api {post} /merchant/reset-api-key/:id 重置API密钥
     * @apiHeader {String} Authorization Bearer token
     * @apiParam {Integer} id API密钥ID
     */
    public function resetApiKey($id)
    {
        $merchantId = $this->getMerchantIdFromToken();
        
        if (!$merchantId) {
            return json(['code' => 401, 'msg' => 'Invalid or expired token']);
        }

        if (empty($id)) {
            return json(['code' => 400, 'msg' => 'API key ID is required']);
        }

        try {
            $result = $this->repository->resetApiKey($merchantId, $id);
            return json($result);
        } catch (\Exception $e) {
            return json([
                'code' => 500,
                'msg' => 'Failed to reset API key: ' . $e->getMessage()
            ]);
        }
    }

    /**
     * 从token中获取商户ID
     */
    private function getMerchantIdFromToken()
    {
        $authHeader = request()->header('Authorization');
        
        if (empty($authHeader)) {
            return null;
        }

        // 提取Bearer token
        if (!preg_match('/Bearer\s+(.*)$/i', $authHeader, $matches)) {
            return null;
        }

        $token = $matches[1];
        
        // 这里应该验证token的有效性
        // 暂时返回模拟的商户ID
        return 1;
    }

    /**
     * 数据验证
     */
    private function validate($data, $rules)
    {
        $errors = [];
        
        foreach ($rules as $field => $rule) {
            $ruleParts = explode('|', $rule);
            $isRequired = in_array('required', $ruleParts);
            
            if ($isRequired && empty($data[$field])) {
                $errors[$field] = "Field {$field} is required";
                continue;
            }
            
            if (!empty($data[$field])) {
                // 邮箱验证
                if (in_array('email', $ruleParts) && !filter_var($data[$field], FILTER_VALIDATE_EMAIL)) {
                    $errors[$field] = "Field {$field} must be a valid email";
                }
                
                // 最小长度验证
                foreach ($ruleParts as $part) {
                    if (strpos($part, 'min:') === 0) {
                        $minLength = intval(substr($part, 4));
                        if (strlen($data[$field]) < $minLength) {
                            $errors[$field] = "Field {$field} must be at least {$minLength} characters";
                        }
                    }
                    
                    if (strpos($part, 'max:') === 0) {
                        $maxLength = intval(substr($part, 4));
                        if (strlen($data[$field]) > $maxLength) {
                            $errors[$field] = "Field {$field} must not exceed {$maxLength} characters";
                        }
                    }
                    
                    if (strpos($part, 'regex:') === 0) {
                        $pattern = substr($part, 6);
                        if (!preg_match($pattern, $data[$field])) {
                            $errors[$field] = "Field {$field} format is invalid";
                        }
                    }
                }
                
                // 确认字段验证
                if (strpos($field, '_confirm') !== false) {
                    $originalField = str_replace('_confirm', '', $field);
                    if (isset($data[$originalField]) && $data[$field] !== $data[$originalField]) {
                        $errors[$field] = "Field {$field} does not match {$originalField}";
                    }
                }
            }
        }
        
        return $errors;
    }
}